<?php

/*2017-4-10 15.45 jack*/
/** 获取上周，本周，上月，本月，本季度，上一季度的时间段
 * @param $type
 * @return array
 */
function get_during_time($type)
{
    $data = array();
    switch($type)
    {
        //上周
        case "last-week" :
        {
            $data['start']      = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y"));
            $data['end']        = mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"));
            break;
        }
        //本周
        case "week" :
        {
            $data['start']      = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
            $data['end']        = mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
            break;
        }

        //本月
        case "month" :
        {
            $data['start']      = mktime(0, 0 , 0,date("m")-1,1,date("Y"));
            $data['end']        = mktime(23,59,59,date("m") ,0,date("Y"));
            break;
        }
        //本季度
        case "last-month" :
        {
            $data['start']      = mktime(0, 0 , 0,date("m"),1,date("Y"));
            $data['end']        = mktime(23,59,59,date("m"),date("t"),date("Y"));
            break;
        }
        case "season" :
        {
            $season = ceil((date('n'))/3);//当月是第几季度
            $data['start']      = mktime(0, 0, 0,$season*3-3+1,1,date('Y'));
            $data['end']        = mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'));
            break;
        }
        //上一季度
        case "last-season" :
        {
            $season = ceil((date('n'))/3)-1;//上季度是第几季度
            $data['start']      = mktime(0, 0, 0,$season*3-3+1,1,date('Y'));
            $data['end']        = mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'));
            break;
        }
    }

    return $data;
}

/*2017-4-10 15.45 jack*/
/** 无限极分类
 * @param array $a 要重构的数组
 * @param int $pid 父类id
 * @param string $id_field id字段
 * @param string $pid_field 父id字段
 * @return array
 */
function get_attr($a,$pid = 0,$id_field,$pid_field,$level = 0){
    //每次都声明一个新数组用来放子元素
    $tree = array();
    foreach($a as $v){
        //匹配子记录
        if($v[$pid_field] == $pid){
            $v['level'] = $level;
            //递归获取子记录
            $v['children'] = get_attr($a,$v[$id_field],$id_field,$pid_field,$level+1);
            if($v['children'] == null){
                //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
                unset($v['children']);
            }
            //将记录存入新数组
            $tree[] = $v;
        }
    }
    //重构后的数组
    return $tree;
}


/**无限极分类，以字符串隔开
 * @param $arr
 * @param $pid
 * @param $step
 * @param string $str 输出的字符
 * @return array
 */
function GetTree($arr,$pid = 0,$step = 0,$str = 'L_'){
    static $tree;
    foreach($arr as $key=>$val) {
        if($val['parent_id'] == $pid) {
            $flg = str_repeat($str,$step);
            $val['name'] = $flg.$val['name'];
            $tree[] = $val;
            GetTree($arr , $val['id'] ,$step+1);
        }
    }
    return $tree;
}

/*删除指定目录下的文件，不删除目录文件夹*/
function delFile($dirName){
    if(file_exists($dirName) && $handle=opendir($dirName)){
        while(false!==($item = readdir($handle))){
            if($item!= "." && $item != ".."){
                if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){
                    delFile($dirName.'/'.$item);
                }else{
                    if(unlink($dirName.'/'.$item)){
                        return true;
                    }
                }
            }
        }
        closedir( $handle);
    }
}


/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

/**
 * 获取post过来的json数据 返回一个数组
 */
function postJsonToArray()
{
    $post = file_get_contents("php://input");
    $post =  json_decode($post,true);
    if(empty($post))
    {
        $post = $_POST;
    }
    return $post;
}

/** 删除不该有的数组键与值
 * @param $data 被删除的数据
 * @param $fields 要保留的键的集合数组
 * @return array
 */
function resetArr($data,$fields)
{
    if(!empty($data) & !empty($fields))
    {
        foreach($data as $k=>$v)
        {
            if(!in_array($k,$fields))
                unset($data[$k]);
        }
    }
    return $data;
}

/**
 * 无限分类数组合并二维数组
 * @param array $arr 无限分类数组
 * @param string $field 子分类字段名
 * @param int $level 级别
 * @return array
 */
function TreeToTwoArr($arr,$field='children')
{
    static $data ;
    if(!empty($arr))
    {
        foreach($arr as $k=>$v)
        {
            //如果存在子类
            if(isset($v[$field]))
            {
                $arr[$k]['hasChild'] = 1;
                //保存该数组的子类数组
                $children = $arr[$k][$field];
                //清空子类数组
                unset($arr[$k][$field]);
                //把该父类数组合并到$data
                $data[] = $arr[$k];
                //从子类数组找
                TreeToTwoArr($children,$field);
            }
            else
            {
                $arr[$k]['hasChild'] = 0;
                //没有子类的数组合并到$data
                $data[] = $arr[$k];
            }

        }
    }
    return $data;
}

/**
 * 给一个数组循环过滤含js代码的
 * @param $arr 要过滤的数组
 * @return array
 */
function ArrRemoveJs($arr)
{
    if(!empty($arr) && is_array($arr))
    {
        foreach($arr as $k=>$v)
        {
            if(is_string($v))
            $arr[$k] = \plugin\filter::remove_js($v);
        }
    }
    return $arr;
}


function exportExcel($args)
{
    header("Content-type:application/vnd.ms-excel;charset=UTF-8");
    header("Content-Disposition:filename=".date('YmdHis')."user_info.xls");
    ob_clean();
    /**
     * args参数说明
     * args.ex_title 代表全文的标题
     * args.data 代表要输出的数据
     * args.ex_th 代表每一列的标题
     */
    $length = count($args['ex_th']) +1 ;
    $table = '
         <table  border="1" align="center">
          <tr>
            <td colspan="'.$length.'" align="center">'.iconv('utf-8', "gb2312", $args['ex_title']).'</td>
          </tr>
          <tr>
    ';
    $table .= "<td>".iconv('utf-8', "gb2312", "编号")."</td>";
    foreach($args['ex_th'] as $v)
    {
        $table .= "<td>".iconv('utf-8', "gb2312", $v)."</td>";
    }
    $table.="</tr>";
    foreach($args['data'] as $k=>$v)
    {
        $table .= "<tr>";
        //编号
        $table .= "<td>".($k+1)."</td>";
        foreach($args['ex_th'] as $k1=>$v1)
        {
            //如果该值是时间字段，并且是10位数
            if(strpos($k1,'time') !== false && intval($v[$k1]) > 1000000000)
            {
                $v[$k1] = date('Y-m-d H:i',$v[$k1]);
            }
            $table .= "<td>".iconv('utf-8', "gb2312", $v[$k1])."</td>";
        }
        $table .= "</tr>";
    }
    $table.="</table>";

    die($table);
}